package com.linzm.leetcode.primary.exercises1_20230114;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zimingl
 * @Date 2023/1/15 1:14
 * @Description: 回文链表
 */
public class Demo10 {
    /**
     * 输入： 1->2->2->1
     * 输出： true
     */
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        head.next = listNode1;
        ListNode listNode2 = new ListNode(2);
        listNode1.next = listNode2;
        ListNode listNode3 = new ListNode(1);
        listNode2.next = listNode3;
        Demo10 demo10 = new Demo10();
        boolean palindrome = demo10.isPalindrome(head);
        System.out.println(palindrome);
    }

    public boolean isPalindrome(ListNode head) {
        if (head.next == null) {
            return true;
        }
        if (head.next.next == null && head.val != head.next.val) {
            return false;
        }
        List<Integer> list = new ArrayList<>();
        list.add(head.val);
        ListNode node = head.next;
        while (node.next != null) {
            list.add(node.val);
            node = node.next;
        }
        list.add(node.val);
        int right = list.size() - 1;
        for (int i = 0; i < right; i++) {
            if (list.get(i) != list.get(right)) {
                return false;
            }
            right--;
        }
        return true;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
